<?php
namespace api\modules\v1\models\report;

use api\modules\common\models\User;
use api\modules\v1\models\group\Group;
use common\models\CacheKeys;
use common\models\Functions;
use common\models\Patterns;
use common\models\Status;
use common\services\upload\Qiniu;
use yii\base\Exception;
use Yii;
/**
 * This is the model class for table "goods".
 *
 * @property int $id
 * @property string $name
 */
class ReportInfo extends \common\models\report\ReportInfo
{
    public function rules()
    {
        return [
            [['content','images','category_id','type','topic_tx_code'],'required','message' => "{attribute}不能为空", 'on' => ['report']],
            [['content'],'filter','filter' => 'trim','on' => ['report']],
            [['content'],'string','min' => '0','max' => '200','message' => "{attribute}需要200字符以内",'on' => ['report']],
            ['content', 'validateImage', 'on' => ['report']],
        ];
    }

    public function attributeLabels()
    {
        return [
            'content' => '描述',
            'images' => '图片',
            'category_id' => '举报分类',
            'type' => '举报类型',
            'topic_tx_code' => '主体ID',
        ];
    }

    /**
     * 设置场景
     * @return array
     */
    public function scenarios()
    {
        $scenarios = [
            'feedback' => [
                'content',
                'images',
                'category_id',
                'type',
                'topic_tx_code',
            ],
        ];
        return array_merge(parent::scenarios(), $scenarios);
    }

    // 验证图片数量
    public function validateImage($attribute) {
        if (!$this->hasErrors()) {
            $config = static::getCommonByKey(['feedback_image_num','feedback_everyday_num']);
            if (count($this->images) > $config['feedback_image_num']) {
                $this->addError($attribute, "举报截图最多{$config['feedback_image_num']}张");
            }
        }
    }


    // 反馈操作
    public function saveInfo() {
        $redis = Yii::$app->redis;
        $user = Yii::$app->getUser()->getIdentity()->toArray();
        try {
            if (!$this->validate()) {
                throw new Exception($this->getErrorSummary(true)[0]);
            }

            CacheKeys::checkFrequency($user['id'],1);
            $exists = $redis->get("REPORT" . $user['id']);
            if($exists){
                throw new Exception('您的速度太快了！');
            }
             // 是否实名
             if ($user['is_kyc'] != Status::COMMON_RADIO_YES) {
                throw new Exception('请先实名认证');
            }
            $post = Yii::$app->request->post();
            $data = [];
            $data = array_merge($data, $this->getSaveData($this->scenario, $post));


            $config = static::getCommonByKey(['feedback_everyday_num']);
            $checkUserCount = static::getCountByWhere(['user_id' => $user['id']]);
            if (($checkUserCount + 1) > $config['feedback_everyday_num']) {
                throw new Exception("每天最多举报{$config['feedback_everyday_num']}次");
            }

            if (!in_array($this->type,array_keys(Status::TOPIC_TYPE_MAP))) {
                throw new Exception('举报类型不合法');
            }

            if ($this->type == Status::QR_CODE_TYPE_USER) {
                $reportUser = User::getOneByWhere(['tx_code' => $this->topic_tx_code]);
                if (!$reportUser) {
                    throw new Exception('被举报用户不存在');
                }
            }

            if ($this->type == Status::QR_CODE_TYPE_GROUP) {
                $reportUser = Group::getOneByWhere(['tx_code' => $this->topic_tx_code]);
                if (!$reportUser) {
                    throw new Exception('被举报群不存在');
                }
            }

            $data["user_id"] = $user['id'];
            $data["images"] = json_encode($this->images);
            $data["create_time"] = date("Y-m-d H:i:s");

            $res = static::insertData($data);
            if ($res === false) {
                throw new Exception('系统异常，请稍后再试');
            }

            return Functions::formatRestAPI(0, '感谢您的举报，我们会尽快核实处理！');
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        } finally {
            $redis->del("REPORT" .  $user['id']);
        }
    }

}
